
  // 引入接口
  import bdApi from "@rc/apis/bd/index.mjs";
  import cbApi from "@rc/apis/cb/index.mjs";
  import rcTagApi from "@rc/apis/rc/tag.mjs";

  // 引入组件
  import CascaderProject from "@rc/pages/components/async/cascader-project.vue";//项目
  export default {
    props: {
        // 是否只显示用户下的项目
        isUserProject: {
            type: Boolean,
            default: false
        },
        // 	菜单code,isUserProject为true时必传
        menuCode: {
            type: String,
            default: ""
        },
    },
    components: {
        CascaderProject
    },
    data() {
      return {
        projectId: '', // 项目id
        ptagId: '', // 子项目id
        subjectId: '', // 科目id
        chapterId:'', //章节id
        projectArr: [], //选择的项目
        projectList: [], // 项目列表
        subProjectList: [], // 子级项目列表
        subjectList: [], // 科目列表
        chapterList: [], // 章节列表
        load: {
            isShowChapterLoading: false// 章节树的loading
        },
        // 章节树配置项
        chapterProps: {
          children: 'children',
          label: 'chapterTitle'
        },
        tabName:'course',// course 系列课 chapter 章节目录
        seriesCourses:[],//系列课列表
        seriesCourseId:'',//系列课id
        courseProps: {
            children: 'children',
            label: 'name'
        },
        defaultExpandedCourse:[],//系列课默认展开项
        defaultExpandedChapter:[]//章节默认展开项
      };
    },
    methods: {
       /**
       * 项目初始化默认选择第一个项目
       */
      onProjectReady(projectList) {
        if(projectList && projectList.length) {
            let projectArr = [];
            const { projectId,  children} = projectList[0];
            projectArr.push(projectId);
            children && children.length && projectArr.push(children[0].projectId);
            this.onProjectChange(projectArr);
        }
      },
      /**
       * 处理项目切换
       * @param projectArr
       */
      onProjectChange(projectArr) {
        this.$emit('get-project-id', projectArr);
        // 清除子级项目和科目信息
        this.subjectList = [];
        this.subProjectList = [];
        this.chapterList = [];
        this.subjectId = '';
        this.seriesCourses = [];
        this.projectArr = projectArr;
        if(projectArr && projectArr.length>1) {
            this.projectId = projectArr[1];
            this.$emit('ready');
            this.queryPtaggroupTree(projectArr[1]);
            this.querySubjectListByProjectId(projectArr[1]);
            this.getSeriesCourse(projectArr[1]);
        }
      },
      /* 获取学员项目下的子级项目
       * @param {object} projectId 请求入参 项目id
       */
      queryPtaggroupTree(projectId) {
        bdApi.queryPtaggroupTree({
            data: {
                projectId: projectId
            },
			success: ({ data }) => {
				this.subProjectList = data;
			}
		});
      },
      /**
       * 切换子级项目
       */
      onPtagIdChange(ptagsArr) {
        this.clearPtagId();
        // 切换的子级项目有值，根据子级项目查询科目
        if(ptagsArr && ptagsArr.length) {
            this.querySubjectListByPtag(ptagsArr[ptagsArr.length-1]);
            this.getSeriesCourse(ptagsArr[ptagsArr.length-1]);
        } else {
          // 根据学院下的项目查询科目
          this.querySubjectListByProjectId(this.projectArr[1]);
          this.getSeriesCourse(this.projectArr[1]);
        }
      },
      /**
       * 子项目切换时需要重置的数据
       */
      clearPtagId() {
        this.subjectList = [];
        this.chapterList = [];
        this.seriesCourses = [];
        this.subjectId = '';
        this.chapterId = '';
      },
      /**
       * 切换科目
       * @param subjectId
       */
      onSubjectChange(subjectId) {
        this.queryChapterTree(subjectId);
      },
      /* 获取项目下的科目树
       * @param {string} projectId 请求入参
       */
      querySubjectListByProjectId(projectId) {
        bdApi.querySubjectListByProjectId({
            data: {
                projectId,
                subjectNature: 'S'
            },
			success: ({ data }) => {
                data.unshift({
                    subjectId: "",
                    subjectName: "全部科目"
                });
				this.subjectList = data;
                if(data && data.length ) {
                    const subjectId = data && data.length ? data[0].subjectId : '';
                    this.subjectId = subjectId;
                    this.queryChapterTree(subjectId);
                }
			}
		});
      },
      /* 根据子级项目下的科目树
       * @param {object} ptagId  子级项目标识
       */
      querySubjectListByPtag(ptagId) {
        this.clearPtagId();
        if( !ptagId ) {
            return;
        }
        bdApi.querySubjectListByPtag({
            data: {
                ptagId
            },
			success: ({ data }) => {
                data.unshift({
                    subjectId: "",
                    subjectName: "全部科目"
                });
				this.subjectList = data;
                if(data && data.length ) {
                    const subjectId = data && data.length ? data[0].subjectId : '';
                    this.subjectId = subjectId;
                    this.queryChapterTree(subjectId);
                }
			}
		});
      },
      /**
       * 获取章节树
       * @param {object} subjectId  科目标识
       */
      queryChapterTree(subjectId) {
        this.chapterList = [];
        this.chapterId = '';
        if(!subjectId) { //切换为全部科目时不查询章节信息
            if(this.tabName==='chapter'){
                this.getCheckedKey();
            }
            return;
        }
        this.load.isShowChapterLoading = true;
        cbApi.queryChapterTree({
            data: {
                projectId:this.projectId,
                subjectId,
                chapterLevel: '2'
            },
			success: (data) => {
                if(data.length) {
                    let chapterList = [{
                        chapterId: 'ZHANGJIEAll',
                        chapterTitle: '全部',
                        children: data
                    }];
                    this.chapterList = chapterList;
                    this.chapterId = 'ZHANGJIEAll';
                    //默认展开所有节点
                    let chapterIds = [];
                    data.forEach(element => {
                        chapterIds.push(element.chapterId);
                        if(element.children){
                            element.children.forEach((children)=>{
                                chapterIds.push(children.chapterId);
                            });
                        }
                    });
                    this.defaultExpandedChapter = ['ZHANGJIEAll',...chapterIds];
                    this.$nextTick(() => {
                        this.$refs.chapterTreeRef.setCurrentKey('ZHANGJIEAll');
                    });
                }
                if(this.tabName==='chapter'){
                    this.getCheckedKey();
                }

			},
            complete: () => {
                this.load.isShowChapterLoading = false;
            }
		});
      },
      /**
       * 处理章节树复选框变化
       */
       onClickChapterTree(checkedNodes) {
        const oldChapterId = this.chapterId;
        // 所有章节 'ZHANGJIEAll'  一级章节不可选中''
        let chapterId = checkedNodes.chapterLevel === 1 ? '' : checkedNodes.chapterId;
        if(checkedNodes.chapterLevel ===1 ) { //一级不可选择，所以还高亮上次选择的结果
            this.$refs.chapterTreeRef.setCurrentKey(this.chapterId);
        }else { // 选择的不是一级，更改当前的章节id
            this.chapterId = chapterId;
            if(oldChapterId!==this.chapterId){
                this.getCheckedKey();
            }
        }

      },
      //切换章节目录和系列课 互斥
      changeTab(tabName){
        if(this.tabName === tabName){
            return;
        }
        this.tabName = tabName;
        if(tabName==='course') {
            this.getSeriesCourse(this.projectId);
            this.chapterId = 'ZHANGJIEAll';
            this.$nextTick(() => {
                this.$refs.chapterTreeRef.setCurrentKey('ZHANGJIEAll');
            });
        }
        if(tabName==='chapter'){
            this.queryChapterTree(this.subjectId);
            this.seriesCourseId = '';
            this.$nextTick(() => {
                this.$refs.courseTreeRef.setCurrentKey('');
            });
        }
      },
    /**
     * 根据项目id获取系列课
     * @param projectId
     * @returns
     */
    getSeriesCourse(projectId) {
        rcTagApi.queryCoursesTreeList({
            data: {
                projectId
            },
            success: (result) => {
                if(result.length){
                    let defaultExpandedCourse = [];
                    const seriesCourses = result.map((teachRange)=>{
                        const {teachRangeCode,teachRangeName,seriesCourses} = teachRange;
                        defaultExpandedCourse.push(teachRangeCode);
                        const children = seriesCourses.map((course)=>{
                            const {id,name} = course;
                            defaultExpandedCourse.push(id);
                            return {
                                seriesId:id,
                                name,
                                isTeachRange:false
                            };
                        });
                        return {
                            seriesId:teachRangeCode,
                            name:teachRangeName,
                            isTeachRange:true,
                            children
                        };
                    });
                    this.seriesCourses = [{
                            seriesId:'',
                            name:'全部',
                            children:seriesCourses
                        }
                    ];
                    //默认展开全部系列课
                    this.defaultExpandedCourse = defaultExpandedCourse;
                    this.seriesCourseId = '';
                    this.$nextTick(() => {
                        this.$refs.courseTreeRef.setCurrentKey('');
                    });
                }
                if(this.tabName==='course'){
                    this.getCheckedKey();
                }
            }
        });
    },
    onClickCourseTree(checkedNodes){
        let oldSeriesCourseId = this.seriesCourseId;
        if(checkedNodes.seriesId && checkedNodes.isTeachRange){// 禁止选择教学阶段
            this.$refs.courseTreeRef.setCurrentKey(this.seriesCourseId);
        } else {//选择的系列课 当系列课改变时重新查询
            this.seriesCourseId = checkedNodes.seriesId;
            if(oldSeriesCourseId!==this.seriesCourseId){
                this.getCheckedKey();
            }
        }
    },
    //所有接口查询完成
    getCheckedKey(){
        this.$emit("get-checked-key",{
            subjectId:this.subjectId,
            chapterId:this.chapterId,
            seriesCourseId:this.seriesCourseId
        });
    }
    }
  };
